package com.qidian.mes.dv.service.impl;

import com.qidian.mes.dv.mapper.SubjectMapper;
import com.qidian.mes.dv.service.SubjectService;
import com.qidian.mes.pojo.dv.Subject;
import com.qidian.mes.util.pojo.MESResult;
import com.qidian.mes.util.pojo.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author 迄氺(甄闯)
 * @Company 空白
 * @Time 2023/10/28 14:26
 * @Description
 */
@Service
@Transactional
public class SubjectServiceImpl implements SubjectService {

    @Autowired
    private SubjectMapper subjectMapper;
    @Override
    public MESResult selectBySubject(Long subjectId) {
        Subject subject = null;
        if ((subject=subjectMapper.selectBySubjectId(subjectId))!=null){
            return MESResult.ok(subject);
        }
        return MESResult.empty();
    }

    @Override
    public MESResult save(Subject subject) {
        //效验名字是否重复
        if(subject.getSubjectName() != null && subjectMapper.selectBySubjectName(subject.getSubjectName()) != null){
            return MESResult.duplicate("项目名重复");
        }
        // updateIsOk会根据传入的参数判断返回的结果
        return MESResult.updateIsOk(subjectMapper.save(subject));
    }

    @Override
    public MESResult queryByPage(Subject subject, int page, int limit) {
        Pager<Subject> pager = new Pager<>();
        pager.setCurr(page);
        pager.setLimit(limit);
        pager.setTotal(subjectMapper.selectCount(subject));
        pager.setData(subjectMapper.selectByPage(subject,(page-1) * limit,limit));
        pager.setMaxPageNum((int)(Math.ceil(pager.getTotal()*1.0 / limit)));

        return MESResult.ok(pager);
    }

    @Override
    public MESResult update(Subject subject) {
        //效验是否重复
        Subject subjectTemp= subjectMapper.selectBySubjectName(subject.getSubjectName());
        if (subjectTemp !=null && !subjectTemp.getSubjectId().equals(subject.getSubjectId())){
            return MESResult.duplicate("用户名重复");
        }
        return MESResult.updateIsOk(subjectMapper.update(subject));
    }

    @Override
    public MESResult deleteById(Long subjectId) {
        return MESResult.updateIsOk(subjectMapper.deleteById(subjectId));
    }
}
